package com.eduagent.xwqeduagent.api.imageTranslation.api;

import com.eduagent.xwqeduagent.api.imageTranslation.constant.ImageTranslationConstant;
import com.eduagent.xwqeduagent.api.imageTranslation.model.ImageInfo;
import com.eduagent.xwqeduagent.api.imageTranslation.model.ImageTranslationResponse;
import com.eduagent.xwqeduagent.api.imageTranslation.util.AuthUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.TreeMap;

/**
 * 图片翻译API实现
 */
@Slf4j
public class ImageTranslationApiImpl implements ImageTranslationApi {

    private final String apiKey;
    private final String appId;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    /**
     * 构造函数
     *
     * @param apiKey API密钥
     * @param appId 应用ID
     */
    public ImageTranslationApiImpl(String apiKey, String appId) {
        this.apiKey = apiKey;
        this.appId = appId;
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
        // 配置ObjectMapper忽略未知属性
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public ImageTranslationResponse uploadAndTranslate(String from, String to, File file, String base64,
                                                       Integer realmCode, String termId, String memoryId) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("from", from);
            params.put("to", to);
            
            // 添加可选参数
            if (realmCode != null) {
                params.put("realmCode", realmCode);
            }
            if (termId != null && !termId.isEmpty()) {
                params.put("termId", termId);
            }
            if (memoryId != null && !memoryId.isEmpty()) {
                params.put("memoryId", memoryId);
            }
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 创建多部分请求
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            for (String key : params.keySet()) {
                body.add(key, params.get(key));
            }
            
            // 添加文件或base64编码
            if (file != null) {
                body.add("file", new FileSystemResource(file));
            } else if (base64 != null && !base64.isEmpty()) {
                body.add("base64", base64);
            } else {
                throw new IllegalArgumentException("必须提供图片文件或base64编码");
            }
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            
            // 创建请求实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            
            // 发送API请求
            ResponseEntity<String> response = restTemplate.exchange(
                    ImageTranslationConstant.UPLOAD_TRANSLATE_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            
            // 解析响应
            ImageTranslationResponse translationResponse = objectMapper.readValue(
                    response.getBody(),
                    ImageTranslationResponse.class
            );
            
            return translationResponse;
        } catch (Exception e) {
            log.error("上传并翻译图片失败: {}", e.getMessage(), e);
            ImageTranslationResponse errorResponse = new ImageTranslationResponse();
            errorResponse.setCode(500);
            errorResponse.setMsg("错误: " + e.getMessage());
            return errorResponse;
        }
    }

    @Override
    public ImageInfo getImageInfo(String fileNo) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 构建URL并添加参数
            String url = String.format(ImageTranslationConstant.STATUS_URL, fileNo);
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            
            // 添加参数到URL
            for (String key : params.keySet()) {
                builder.queryParam(key, params.get(key));
            }
            
            // 发送API请求
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.GET,
                    null,
                    String.class
            );
            
            // 解析响应
            ImageTranslationResponse translationResponse = objectMapper.readValue(
                    response.getBody(),
                    ImageTranslationResponse.class
            );
            
            // 将data转换为ImageInfo对象
            if (translationResponse.getCode() == 200 && translationResponse.getData() != null) {
                String dataJson = objectMapper.writeValueAsString(translationResponse.getData());
                return objectMapper.readValue(dataJson, ImageInfo.class);
            } else {
                log.error("获取图片信息失败: {}", translationResponse.getMsg());
                return null;
            }
        } catch (Exception e) {
            log.error("获取图片信息异常: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public boolean interruptTranslation(String fileNo) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 构建URL并添加参数
            String url = String.format(ImageTranslationConstant.INTERRUPT_URL, fileNo);
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            
            // 添加参数到URL
            for (String key : params.keySet()) {
                builder.queryParam(key, params.get(key));
            }
            
            // 发送API请求
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.PUT,
                    null,
                    String.class
            );
            
            // 解析响应
            ImageTranslationResponse translationResponse = objectMapper.readValue(
                    response.getBody(),
                    ImageTranslationResponse.class
            );
            
            // 检查是否成功
            if (translationResponse.getCode() == 200 && translationResponse.getData() != null) {
                return Boolean.TRUE.equals(translationResponse.getData());
            } else {
                log.error("中断图片翻译失败: {}", translationResponse.getMsg());
                return false;
            }
        } catch (Exception e) {
            log.error("中断图片翻译异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public String getDownloadUrl(String fileNo, Integer type) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("type", type);
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 构建URL并添加参数
            String url = String.format(ImageTranslationConstant.DOWNLOAD_URL_ENDPOINT, fileNo);
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            
            // 添加参数到URL
            for (String key : params.keySet()) {
                builder.queryParam(key, params.get(key));
            }
            
            // 发送API请求
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.GET,
                    null,
                    String.class
            );
            
            // 解析响应
            ImageTranslationResponse translationResponse = objectMapper.readValue(
                    response.getBody(),
                    ImageTranslationResponse.class
            );
            
            // 获取下载URL
            if (translationResponse.getCode() == 200 && translationResponse.getData() != null) {
                return translationResponse.getData().toString();
            } else {
                log.error("获取下载链接失败: {}", translationResponse.getMsg());
                return null;
            }
        } catch (Exception e) {
            log.error("获取下载链接异常: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public InputStream downloadImage(String fileNo, Integer type) {
        try {
            // 获取下载链接
            String downloadUrl = getDownloadUrl(fileNo, type);
            if (downloadUrl == null || downloadUrl.isEmpty()) {
                return null;
            }
            
            // 从URL下载文件流
            URL url = new URL(downloadUrl);
            return url.openStream();
        } catch (IOException e) {
            log.error("下载图片异常: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public boolean deleteImage(String fileNo) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 构建URL并添加参数
            String url = String.format(ImageTranslationConstant.DELETE_URL, fileNo);
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            
            // 添加参数到URL
            for (String key : params.keySet()) {
                builder.queryParam(key, params.get(key));
            }
            
            // 发送API请求
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.DELETE,
                    null,
                    String.class
            );
            
            // 解析响应
            ImageTranslationResponse translationResponse = objectMapper.readValue(
                    response.getBody(),
                    ImageTranslationResponse.class
            );
            
            // 检查是否成功
            if (translationResponse.getCode() == 200 && translationResponse.getData() != null) {
                return Boolean.TRUE.equals(translationResponse.getData());
            } else {
                log.error("删除图片翻译失败: {}", translationResponse.getMsg());
                return false;
            }
        } catch (Exception e) {
            log.error("删除图片翻译异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Object translateImageSync(String from, String to, File file, String base64, Integer resultType,
                                    Integer realmCode, String termId, String memoryId) {
        try {
            // 创建参数Map
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("from", from);
            params.put("to", to);
            
            // 添加可选参数
            if (resultType != null) {
                params.put("resultType", resultType);
            }
            if (realmCode != null) {
                params.put("realmCode", realmCode);
            }
            if (termId != null && !termId.isEmpty()) {
                params.put("termId", termId);
            }
            if (memoryId != null && !memoryId.isEmpty()) {
                params.put("memoryId", memoryId);
            }
            
            // 生成认证参数
            params = AuthUtils.generateAuthParams(params, apiKey, appId);
            
            // 创建多部分请求
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            for (String key : params.keySet()) {
                body.add(key, params.get(key));
            }
            
            // 添加文件或base64编码
            if (file != null) {
                body.add("file", new FileSystemResource(file));
            } else if (base64 != null && !base64.isEmpty()) {
                body.add("base64", base64);
            } else {
                throw new IllegalArgumentException("必须提供图片文件或base64编码");
            }
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            
            // 创建请求实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            
            // 根据resultType决定返回格式
            if (resultType != null && resultType == ImageTranslationConstant.ResultType.BASE64) {
                // 返回base64编码
                ResponseEntity<byte[]> response = restTemplate.exchange(
                        ImageTranslationConstant.SYNC_TRANSLATE_URL,
                        HttpMethod.POST,
                        requestEntity,
                        byte[].class
                );
                
                // 将字节数组转换为字符串
                if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                    return new String(response.getBody());
                }
            } else {
                // 返回文件流或JSON响应
                ResponseEntity<Object> response = restTemplate.exchange(
                        ImageTranslationConstant.SYNC_TRANSLATE_URL,
                        HttpMethod.POST,
                        requestEntity,
                        Object.class
                );
                
                return response.getBody();
            }
            
            // 如果失败返回错误响应
            log.error("同步翻译图片失败");
            return null;
        } catch (Exception e) {
            log.error("同步翻译图片异常: {}", e.getMessage(), e);
            return null;
        }
    }
} 